<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>淘好货 - 购物车</title>
    <!-- 引入 Tailwind CSS -->
    <script src="/static/css/tailwindcss.css"></script>
    <!-- 引入 Font Awesome 图标库 -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- 自定义 Tailwind 配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#FF4400', // 主色调：橙色
                        secondary: '#FFB800', // 辅助色：黄色
                        dark: '#333333',    // 深色文本
                        light: '#F5F5F5',   // 浅色背景
                        muted: '#666666',   // 次要文本
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif']
                    }
                }
            }
        }
    </script>
    <!-- 自定义样式 -->
    <style>
        /* 复选框样式 */
        .custom-checkbox {
            appearance: none;
            -webkit-appearance: none;
            width: 20px;
            height: 20px;
            border: 2px solid #d1d5db;
            border-radius: 4px;
            outline: none;
            cursor: pointer;
            position: relative;
            margin-right: 12px;
            vertical-align: middle;
        }

        .custom-checkbox:checked {
            background-color: #FF4400;
            border-color: #FF4400;
        }

        .custom-checkbox:checked::after {
            content: "";
            position: absolute;
            left: 6px;
            top: 2px;
            width: 5px;
            height: 10px;
            border: solid white;
            border-width: 0 2px 2px 0;
            transform: rotate(45deg);
        }

        /* 数量控制容器 - 左右排版 */
        .quantity-control {
            display: flex;
            align-items: center;
            border: 1px solid #e5e7eb; /* 浅灰色边框 */
            border-radius: 4px; /* 更圆润的边角 */
            overflow: hidden; /* 隐藏超出的按钮边角 */
            height: 40px; /* 增加高度提升点击区域 */
            margin: 4px 0; /* 调整上下边距 */
            width: fit-content; /* 自适应内容宽度 */
        }

        /* 数量控制按钮 - 通用样式 */
        .control-btn {
            width: 36px; /* 增大按钮尺寸 */
            height: 100%; /* 撑满容器高度 */
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.125rem; /* 调整字体大小 */
            font-weight: 500; /* 适中的字体粗细 */
            cursor: pointer;
            background-color: #fff; /* 白色背景 */
            transition: all 0.2s ease; /* 更快速的过渡效果 */
            border: none;
        }

        /* 左右箭头按钮 - 单独样式 */
        .control-btn:first-child {
            border-right: 1px solid #e5e7eb; /* 中间分隔线 */
            border-radius: 4px 0 0 4px; /* 左侧圆角 */
        }

        .control-btn:last-child {
            border-left: 1px solid #e5e7eb; /* 中间分隔线 */
            border-radius: 0 4px 4px 0; /* 右侧圆角 */
        }

        /* 悬停状态 */
        .control-btn:hover {
            background-color: #FF44001A; /* 透明橙色悬停背景 */
            color: #FF4400; /* 加深文字颜色 */
        }

        /* 激活状态（点击时） */
        .control-btn:active {
            background-color: #FF440033; /* 更深的悬停背景 */
        }

        /* 禁用状态 */
        .control-btn:disabled {
            background-color: #f3f4f6;
            color: #d1d5db;
            cursor: not-allowed;
        }

        /* 数量显示 - 中间文本 */
        .quantity-number {
            padding: 0 12px; /* 左右内边距 */
            font-size: 1rem;
            font-weight: 500;
            color: #333;
        }

        /* 结算按钮 */
        .checkout-btn {
            padding: 12px 24px;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            color: white;
            background-color: #FF4400;
            transition: all 0.3s ease;
            border: none;
            min-width: 160px;
        }

        .checkout-btn:hover {
            background-color: #d93b00;
        }

        .checkout-btn:disabled {
            background-color: #f3f4f6;
            color: #6b7280;
            cursor: not-allowed;
        }

        /* 删除按钮 */
        .delete-btn {
            color: #ef4444;
            transition: all 0.3s ease;
            background: none;
            border: none;
            cursor: pointer;
            font-size: 18px;
        }

        .delete-btn:hover {
            color: #dc2626;
        }

        /* 商品项布局 */
        .cart-item-content {
            display: flex;
            align-items: center;
            width: 100%;
            gap: 16px;
        }

        @media (max-width: 768px) {
            .cart-item-content {
                flex-wrap: wrap;
            }

            .quantity-control {
                order: 3;
                margin-left: auto;
            }

            .subtotal {
                order: 4;
                width: 100%;
                text-align: right;
                margin-top: 8px;
            }
        }
    </style>
</head>
<body class="font-sans bg-gray-50 text-dark">
<div id="app">
    <!-- 导航栏组件 -->
    <navigation></navigation>

    <!-- 购物车主内容 -->
    <main class="container mx-auto px-4 py-8">
        <div class="flex justify-between items-center mb-6">
            <h1 class="text-2xl font-bold">我的购物车</h1>
            <div class="flex items-center">
                <span class="mr-2 text-gray-600">已选择:</span>
                <span class="selected-count" v-if="selectedItems.length > 0">{{ selectedItems.length }}件商品</span>
                <span class="text-gray-400" v-else>0</span>
            </div>
        </div>

        <!-- 购物车为空提示 -->
        <div v-if="cartItems.length === 0" class="empty-cart bg-white rounded-lg shadow-md p-12 text-center">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-24 w-24 text-primary mx-auto" fill="none"
                 viewBox="0 0 24 24"
                 stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                      d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
            </svg>
            <p class="mt-4 text-lg text-gray-600">您的购物车是空的</p>
            <a href="/" class="mt-6 checkout-btn inline-block">去购物</a>
        </div>

        <!-- 购物车有商品 -->
        <div v-else class="bg-white rounded-lg shadow-md overflow-hidden">
            <!-- 商品列表 -->
            <div class="divide-y divide-gray-200">
                <div v-for="(item, index) in cartItems" :key="item.id || index" class="cart-item p-4">
                    <div class="cart-item-content">
                        <!-- 复选框 -->
                        <input type="checkbox"
                               class="custom-checkbox"
                               v-model="item.selected"
                        >

                        <!-- 商品图片 -->
                        <img :src="item.image" alt=""
                             class="w-20 h-20 object-cover rounded-lg shadow-sm flex-shrink-0"/>

                        <!-- 商品信息 -->
                        <div class="flex-1 min-w-0">
                            <h3 class="font-medium text-lg truncate">{{ item.product_name }}</h3>
                            <p class="text-gray-600">单价：¥{{ item.price.toFixed(2) }}</p>
                        </div>

                        <!-- 数量控制 -->
                        <div class="quantity-control">
                            <button @click="decreaseQuantity(item)" class="control-btn" :disabled="item.quantity <= 1">
                                -
                            </button>
                            <span class="quantity-number">{{ item.quantity }}</span>
                            <button @click="increaseQuantity(item)" class="control-btn">+</button>
                        </div>

                        <!-- 小计 -->
                        <span class="subtotal font-medium text-primary whitespace-nowrap">
                            小计：¥{{ (item.price * item.quantity).toFixed(2) }}
                        </span>

                        <!-- 删除按钮 -->
                        <button @click="removeItem(item)" class="delete-btn ml-2">
                            <i class="fa fa-trash"></i>
                        </button>
                    </div>
                </div>
            </div>

            <!-- 结算栏 -->
            <div class="cart-footer p-6 bg-gray-50">
                <div class="flex flex-col md:flex-row justify-between items-center gap-4">
                    <div class="flex items-center">
                        <!-- 全选复选框 -->
                        <input type="checkbox"
                               class="custom-checkbox mr-2"
                               v-model="selectAll"
                               @change="handleSelectAll">
                        <label class="text-gray-600 mr-4">全选</label>
                        <button @click="clearSelected" class="text-gray-500 hover:text-gray-700 transition-colors"
                                :disabled="selectedItems.length === 0">
                            清除选中
                        </button>
                    </div>

                    <div class="flex flex-col md:flex-row items-center gap-4">
                        <div class="text-right">
                            <p class="text-gray-600">总计：<span
                                    class="font-bold text-xl text-primary">¥{{ selectedTotalPrice.toFixed(2) }}</span>
                            </p>
                            <p class="text-sm text-gray-500">(已选择 {{ selectedItems.length }} 件商品)</p>
                        </div>
                        <button @click="handleCheckout" class="checkout-btn"
                                :disabled="selectedItems.length === 0 || isCheckingOut">
                            {{ isCheckingOut ? '结算中...' : '结算' }}
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <!-- 页脚 -->
    <app-footer></app-footer>
</div>
<script src="/static/js/vue.js"></script>
<script src="/static/js/top.js"></script>
<script src="/static/js/foot.js"></script>
<script src="/static/js/common.js"></script>
<script src="/static/js/message.js"></script>
<script>
    new Vue({
        el: '#app',
        data: {
            util,
            cartItems: [],
            isCheckingOut: false,
            selectAll: false
        },
        computed: {
            cartItemCount() {
                return this.cartItems.reduce((acc, item) => acc + item.quantity, 0);
            },
            totalPrice() {
                return this.cartItems.reduce((acc, item) => acc + (item.price * item.quantity), 0);
            },
            selectedItems() {
                return this.cartItems.filter(item => item.selected);
            },
            selectedTotalPrice() {
                return this.selectedItems.reduce((acc, item) => acc + (item.price * item.quantity), 0);
            }
        },
        watch: {
            // 观察购物车中所有商品的选择状态
            cartItems: {
                deep: true,
                handler(newItems) {
                    if (newItems.length === 0) {
                        this.selectAll = false;
                        return;
                    }

                    const allSelected = newItems.every(item => item.selected);
                    if (this.selectAll !== allSelected) {
                        this.selectAll = allSelected;
                    }
                }
            }
        },
        methods: {
            // 加载购物车数据
            async loadCarts() {
                try {
                    const response = await fetch('/carts');
                    if (response.ok) {
                        const res = await response.json();
                        this.cartItems = res.data;
                    } else {
                        const error = await response.json();
                        message.error(error.message);
                    }
                } catch (error) {
                    message.error('网络错误，请稍后重试');
                }
            },
            //修改购物车数量
            async updateCarts(item) {
                try {
                    const data = {
                        'quantity': item.quantity
                    }
                    const response = await fetch(`/carts/${item.id}`, {
                        method: 'PUT',
                        headers: {'Content-Type': 'application/json'},
                        body: JSON.stringify(data)
                    });
                    if (!response.ok) {
                        const error = await response.json();
                        message.error(error.message);
                    }
                } catch (error) {
                    message.error('网络错误，请稍后重试');
                }
            },
            //移除购物车
            async removeCarts(item) {
                try {
                    const response = await fetch(`/carts/${item.id}`, {
                        method: 'DELETE',
                    });
                    if (!response.ok) {
                        const error = await response.json();
                        message.error(error.message);
                    }else {
                        this.loadCarts();
                    }
                } catch (error) {
                    message.error('网络错误，请稍后重试');
                }
            },
            increaseQuantity(item) {
                item.quantity++;
                this.updateCarts(item)
            },
            decreaseQuantity(item) {
                if (item.quantity > 1) {
                    item.quantity--;
                    this.updateCarts(item)
                }
            },
            removeItem(item) {
                // 先调用后端接口删除
                this.removeCarts(item)
            },
            handleSelectAll() {
                // 使用 Vue.set 确保响应式更新
                this.cartItems.forEach((item, index) => {
                    this.$set(this.cartItems, index, {
                        ...item,
                        selected: this.selectAll
                    });
                });
            },
            clearSelected() {
                this.cartItems.forEach(item => {
                    item.selected = false;
                });
                this.selectAll = false;
            },
            handleCheckout() {
                if (this.selectedItems.length === 0) {
                    message.error('请选择要结算的商品');
                    return;
                }

                this.isCheckingOut = true;
                // 模拟延迟
                setTimeout(() => {
                    //存储购物车的数据
                    localStorage.setItem('cart', JSON.stringify(this.cartItems))
                    window.location.href = '/settle';
                }, 2000);
            }
        },
        created() {
            util.store.set("return-url", location.href);
            if (this.util.isLogin()) {
                this.loadCarts();
            } else location.href = '/login';
        }
    });
</script>
</body>
</html>